Popular Searches
Popular Course Categories
Popular Courses

JSX Elements

JSX Elements

JSX in React

JSX Elements in React JS – Detailed Notes

JSX Elements are a fundamental part of React JS. They describe the user interface that React should display, including headings, paragraphs, buttons, images, lists, and custom React components. JSX allows developers to write HTML-like markup inside JavaScript code, making user interfaces easier to create and understand.

These notes cover JSX elements from beginner to practical level, including syntax, rules, examples, differences between elements and components, common errors, interview questions, and revision points.


1. What Are JSX Elements?

A JSX element is an expression written using JSX syntax that describes a piece of user interface. It can represent a heading, paragraph, button, image, or another React component.

Example:

const heading = <h1>Welcome to React JS</h1>;
const message = <p>Learn React step by step.</p>;
const button = <button>Get Started</button>;

In this example, heading, message, and button store JSX elements in JavaScript variables. React can use these elements to describe what should appear in the user interface.

JSX looks similar to HTML, but it is a JavaScript syntax extension and follows some additional rules. Read the official React guide to writing markup with JSX.


2. Basic Syntax of JSX Elements

A JSX element generally consists of an opening tag, content, and a closing tag. Some elements, such as images, use self-closing syntax.

Syntax:

const element = <tagName>Content</tagName>;

Example:

function App() {
  return (
    <div>
      <h1>Hello, React!</h1>
      <p>This is my first JSX element.</p>
    </div>
  );
}
export default App;

Here, div, h1, and p are JSX tags. The entire JSX expression describes a user interface containing a heading and a paragraph inside a parent element.


3. Types of JSX Elements

3.1 HTML-like Elements

These elements represent standard HTML elements such as headings, paragraphs, links, buttons, and images.

function App() {
  return (
    <div>
      <h1>My Website</h1>
      <p>Welcome to my website.</p>
      <a href="https://example.com">Visit Website</a>
      <button>Click Here</button>
    </div>
  );
}

3.2 Custom Component Elements

React components can be used as JSX elements. Component names must begin with a capital letter.

function Welcome() {
  return <h1>Welcome to React JS</h1>;
}

function App() {
  return (
    <div>
      <Welcome />
    </div>
  );
}

Here, is a JSX element that tells React to render the Welcome component.

3.3 Nested JSX Elements

One JSX element can contain other JSX elements. This is called nesting.

function App() {
  return (
    <section>
      <h1>Our Courses</h1>
      <div>
        <h2>React JS Training</h2>
        <p>Learn to build interactive web applications.</p>
      </div>
    </section>
  );
}

Nesting helps developers create structured layouts and organize content logically.


4. Important Rules of JSX Elements

Rule 1: Return a Single Root Element

When returning multiple JSX elements from a component, wrap them in one parent element or a React Fragment.

Incorrect:

function App() {
  return (
    <h1>Hello</h1>
    <p>Welcome to React</p>
  );
}

Correct using a parent element:

function App() {
  return (
    <div>
      <h1>Hello</h1>
      <p>Welcome to React</p>
    </div>
  );
}

Correct using a Fragment:

function App() {
  return (
    <>
      <h1>Hello</h1>
      <p>Welcome to React</p>
    </>
  );
}

A Fragment groups elements without adding an extra DOM element to the rendered HTML.

Rule 2: Close All Tags

JSX requires every tag to be properly closed. Self-closing elements must end with />.

Incorrect:

<img src="photo.png">
<input type="text">

Correct:

<img src="photo.png" alt="Sample photo" />
<input type="text" />

Regular elements also need closing tags:

<p>This is a paragraph.</p>

Rule 3: Use Correct JSX Attribute Names

Some JSX attributes differ from their HTML equivalents. For example, use className instead of class and htmlFor instead of for.

function App() {
  return (
    <div className="container">
      <label htmlFor="username">Username</label>
      <input id="username" type="text" />
    </div>
  );
}

Rule 4: Use Curly Braces for JavaScript Expressions

Curly braces allow you to include JavaScript expressions inside JSX.

function App() {
  const name = "Aarav";
  const age = 21;

  return (
    <div>
      <h1>Hello, {name}!</h1>
      <p>Age: {age}</p>
      <p>Next year: {age + 1}</p>
    </div>
  );
}

The expressions inside curly braces are evaluated by JavaScript, and their renderable results are included in the UI.


5. JSX Elements and JavaScript Expressions

JSX elements can be assigned to variables, passed to functions, included in arrays, and returned from components. This makes them flexible and reusable.

Example:

function App() {
  const title = <h1>React JS Tutorial</h1>;
  const description = <p>Learn JSX elements with examples.</p>;

  return (
    <div>
      {title}
      {description}
    </div>
  );
}

In this example, JSX elements are stored in variables and then included in the returned JSX through curly braces.

Important: A JavaScript expression can produce a JSX element, but JSX itself is not an HTML string. A JSX element describes UI for React to render.


6. Displaying Dynamic Data in JSX Elements

JSX elements can display data stored in variables or calculated through expressions.

function App() {
  const studentName = "Riya";
  const marks = 85;

  return (
    <div>
      <h1>Student Details</h1>
      <p>Name: {studentName}</p>
      <p>Marks: {marks}</p>
      <p>Result: {marks >= 40 ? "Pass" : "Fail"}</p>
    </div>
  );
}

This example uses variables and a ternary expression to display dynamic information.

Common uses include:

  • Displaying user names and profile information.
  • Showing product names, prices, and availability.
  • Displaying scores, totals, and calculated values.
  • Showing different messages depending on a condition.

7. Using JSX Elements with Conditional Rendering

Conditional rendering means displaying different elements depending on a condition.

7.1 Using the Ternary Operator

function App() {
  const isLoggedIn = true;

  return (
    <div>
      {isLoggedIn
        ? <h1>Welcome Back!</h1>
        : <h1>Please Log In</h1>}
    </div>
  );
}

7.2 Using the Logical AND Operator

function App() {
  const showMessage = true;

  return (
    <div>
      {showMessage && <p>Your profile has been updated.</p>}
    </div>
  );
}

The paragraph appears when showMessage is true. Be careful when using && with a number: an expression such as {count &&

Items

} can render 0 when count is zero. Use count > 0 && ... when that is the intended behavior.


8. Rendering Lists of JSX Elements

React commonly uses JavaScript's map() method to convert an array of data into an array of JSX elements.

function App() {
  const courses = ["React JS", "JavaScript", "HTML", "CSS"];

  return (
    <div>
      <h1>Available Courses</h1>
      <ul>
        {courses.map((course) => (
          <li key={course}>{course}</li>
        ))}
      </ul>
    </div>
  );
}

The map() method creates a list item for each course. The key prop helps React identify list items when the list changes. In real applications, use a stable, unique ID where available rather than relying on array positions for lists that can be reordered or modified.


9. Difference Between JSX Elements and React Components

JSX elements and React components are related, but they are not the same thing.

Basis JSX Element React Component
Meaning Describes a piece of UI. A reusable unit of UI logic and rendering.
Example

Hello

function Welcome() { return

Hello

; }
Usage Can be rendered or included in other JSX. Can be used to create JSX elements such as .
Reusability An element can be reused as a value, but it is not a component definition. Components can be reused with different props.
Naming HTML-like tags are generally lowercase; custom component tags start with a capital letter. Component names must begin with a capital letter.

Example:

// React component
function Welcome() {
  return <h1>Hello, React!</h1>;
}

// JSX element that represents the component
const element = <Welcome />;

Here, Welcome is the component, while is the JSX element used to render it.


10. JSX Elements and the React Virtual DOM

JSX syntax is transformed by development tools into JavaScript calls or equivalent structures. In modern React tooling, JSX is commonly compiled using the automatic JSX runtime. React elements describe the UI that should be rendered.

React compares the UI descriptions from one render with the next and updates the necessary parts of the browser DOM. The Virtual DOM is a common teaching term for React's in-memory representation and reconciliation process; a JSX element itself is not a browser DOM node.

Example:

const element = <h1>Hello World</h1>;

The expression creates a React element description. React uses that description when rendering the UI; it does not immediately create a real DOM node simply because the JSX expression was evaluated.


11. JSX Elements with Attributes

JSX elements can contain attributes that configure their appearance, behavior, or data.

function App() {
  const imageUrl = "/images/react-logo.png";

  return (
    <div className="profile-card">
      <img src={imageUrl} alt="React logo" width={150} />
      <h2 title="React Course">React JS Training</h2>
      <button onClick={() => alert("Course selected")}>
        View Course
      </button>
    </div>
  );
}

In this example:

  • className assigns a CSS class.
  • src sets the image source.
  • alt provides alternative text for the image.
  • width sets the image width.
  • title provides additional descriptive text.
  • onClick registers a click handler.

12. Common Mistakes When Working with JSX Elements

Mistake Correct Approach Explanation
Returning multiple adjacent root elements. Wrap them in a parent or Fragment. A component must return one root JSX expression.
Leaving a tag unclosed. Close every tag or use self-closing syntax. JSX has stricter tag rules than HTML.
Using class. Use className. JSX uses JavaScript-compatible attribute names.
Writing for a custom component. Use . Custom component names start with a capital letter.
Writing return and starting JSX on the next line without parentheses. Use return (
...
)
.
JavaScript automatic semicolon insertion can make the function return undefined.
Using a plain object as a child. Render an appropriate property or map the data into elements. Ordinary objects are not directly renderable as children.
Rendering lists without keys. Provide stable, unique keys. Keys help React track list items across updates.
Writing HTML comments directly inside JSX. Use {/* comment */}. JSX comments use JavaScript comment syntax inside braces.

13. Practical Example: Student Information Card

The following example combines JSX elements, attributes, JavaScript expressions, conditional rendering, and nested elements.

function StudentCard() {
  const student = {
    name: "Ananya Sharma",
    course: "React JS",
    score: 88,
    isEnrolled: true
  };

  return (
    <div className="student-card">
      <h1>Student Information</h1>
      <h2>{student.name}</h2>
      <p>Course: {student.course}</p>
      <p>Score: {student.score}%</p>
      <p>
        Status: {student.isEnrolled ? "Enrolled" : "Not Enrolled"}
      </p>
      {student.score >= 80 && <p>Excellent Performance!</p>}
    </div>
  );
}

export default StudentCard;

Concepts covered:

  • Parent and child JSX elements.
  • Dynamic values through JavaScript expressions.
  • Conditional rendering using the ternary operator.
  • Conditional display using the logical AND operator.
  • CSS classes using className.

14. Best Practices for JSX Elements

  • Keep JSX readable by using consistent indentation.
  • Use one clear root element or a Fragment when returning multiple elements.
  • Close every element properly.
  • Use meaningful component names that start with capital letters.
  • Keep complex logic outside JSX when doing so improves readability.
  • Use curly braces to insert JavaScript expressions.
  • Use stable keys when rendering lists.
  • Use semantic HTML elements such as main, section, nav, and button appropriately.
  • Provide meaningful alternative text for informative images.
  • Break large interfaces into small, reusable components.
  • Use the browser console and React development tools to troubleshoot errors.

15. Interview Questions and Answers on JSX Elements

Q1. What is a JSX element?

A JSX element is an expression that describes a piece of user interface, such as a heading, paragraph, button, or React component.

Q2. Is JSX the same as HTML?

No. JSX looks similar to HTML, but it is a JavaScript syntax extension with rules such as closing all tags, using a single root element, and using JSX-specific attribute names.

Q3. Can a JSX element be stored in a variable?

Yes. For example, const heading =

Hello

; stores a JSX element in a variable.

Q4. Why must multiple JSX elements have a common parent?

A component must return one root JSX expression. A parent element or Fragment groups multiple child elements into that single expression.

Q5. What is a React Fragment?

A Fragment groups multiple JSX elements without adding an extra DOM element. Its shorthand syntax is <>....

Q6. What is the difference between a JSX element and a component?

A component is a reusable function or other supported component definition that returns UI. A JSX element is a description of UI, such as

Hello

or .

Q7. Can JavaScript expressions be used inside JSX?

Yes. Use curly braces to include expressions, for example,

Total: {10 + 20}

.

Q8. How do you render an array as JSX elements?

Use methods such as map() to transform array items into JSX elements and provide a stable key for each item.

Q9. Why are keys important in lists?

Keys help React identify which list items have changed, been added, or been removed during updates.

Q10. How do you write comments in JSX?

Write comments inside curly braces using JavaScript comment syntax, such as {/* This is a JSX comment */}.


16. Quick Revision Checklist

  • Understand the meaning of JSX elements.
  • Know the basic JSX syntax.
  • Recognize HTML-like, nested, and component JSX elements.
  • Remember the single-root rule and Fragment syntax.
  • Close all tags correctly.
  • Use JavaScript expressions inside curly braces.
  • Understand conditional rendering.
  • Render arrays with map() and stable keys.
  • Understand the difference between elements and components.
  • Recognize common JSX mistakes and how to fix them.
  • Practice building a student card or product card.

17. Conclusion

JSX elements are one of the core building blocks of React JS. They describe the interface that React should render and make it possible to combine markup with JavaScript expressions. By understanding JSX syntax, nesting, fragments, dynamic values, conditional rendering, lists, and component elements, you can build structured and reusable user interfaces.

After learning JSX elements, continue with JSX attributes, JSX expressions, components, props, state, event handling, and conditional rendering.

Useful React JS Training Links

whatsapp